#!/usr/bin/env python
# -*- coding: utf-8 -*-
import json

from flask import jsonify, request
from flask_restful import Resource
from utility.odoo_manager import OdooManager  # 操作odoo的单例
from utility.error_code import error_code  # 异常代码
from utility.message_manager import MessageBusManager
from event import event_type
from command import command
import logging
from utility import tools
from command.handler import dict_handler
from utility.tools import is_checking, nullablea_dict, check_progress, update_archives

FORMAT = "%(asctime)s %(thread)d %(message)s"
logging.basicConfig(level=logging.INFO, format=FORMAT)


class DiagnosticRecordAddAPI(Resource):
    """
    新增诊断处理
    :request: post
    :param archivesId: 档案ID
    :param checkType: 类型 1 初检 2常规 3 产后42天
    :param zsybz: 主诉与病状
            {
                "zszzFt": 腹痛
                "zszzYdcx": 阴道出血
                "zszzYdyy": 阴道溢液
                "zszzPfwy": 皮肤瘟痒
                "zszzHxkn": 呼吸困难
                "zszzTy": 头晕
                "zszzYh": 眼花
                "zszzFr": 发热
                "zszzTdyc": 胎动异常
                "zszzSktt": 伤口疼痛
                "zszzQt": 其他
            }
    :param gwsc: 高危筛查
            {
                "gwscKg": 高危因素判定开关
                "gwys": 高危因素
                    [
                        {
                            "gwysflCode": 高危因素分类编码
                            "gwysflName": 高危因素分类名
                            "gwysBm": 高危因素编码
                            "gwysMc": 高危因素名称
                            "gwColor": 高危因素颜色
                            "gwColorCode": 高危因素颜色编码
                        }
                    ]
            }
    :param gwpg: 高危评估
            {
                "gwpgGxpg": 高危颜色-开关-1 0
                "gwpgGwys": 高危评估颜色
            }
    :param jcxm: 常规检查项目
            {
                "cgjcxm": 常规检查项目
                    [
                        {
                            "cgjcxmCode": 常规检查项目编码
                            "cgjcxmName": 常规检查项目名称
                        }
                    ],
                "fzjcxm": 辅助检查项目
                    [
                        {
                            "fzjcxmCode": 辅助检查项目编码
                            "fzjcxmName": 辅助检查名称
                        }
                    ]
            }
    :param zdyzdyj: 诊断与指导意见
            {
                "yc": 孕次
                "cc": 产次
                "yz": 孕周
                "zd": 诊断
                "zdyj": 知道意见
                "bjzd": 保健指导
                    [
                        {
                            "bjzdCode": 保健指导CODE
                            "bjzdName": 保健指导名称
                        }
                    ]
            }
    :param cl: 处理
            {
                "clZz": 是否转诊
                "clZzjg": 转诊机构
                "clZzks": 转诊科室
                "clZzyy": 转诊原因
                "clYy": 是否预约
                "clXccjsj": 下次产检时间
                "clZdsj": 诊断时间
                "clYsId": 医生ID
                "clYsName": 医生姓名
                "pg": 评估 产后42天才有
                "cl": 处理 产后42天才有
            }
    :returns: json string
    """
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            # 参数校验
            req_params = ['archivesId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            check_res = is_checking(params.get("archivesId"), str(params.get('checkType')))
            if not check_res['res']:
                return jsonify({
                    'code': 1,
                    'msg': check_res['msg'],
                    'data': None
                })
            progress_data = check_progress(params.get('archivesId'), params.get('checkType'))
            if not progress_data['data']:
                return jsonify({
                    'msg': progress_data['msg'],
                    'code': 1
                })
            # 新增诊断处理
            data_={
                #'inspection_log_id': '',
                'archives_id': params.get('archivesId'),
                'type': params.get('checkType'),
                'zszz_ft': nullablea_dict(params.get('zsybz'), 'zszzFt'),
                'zszz_ydcx': nullablea_dict(params.get('zsybz'), 'zszzYdcx'),
                'zszz_ydyy': nullablea_dict(params.get('zsybz'), 'zszzYdyy'),
                'zszz_pfwy': nullablea_dict(params.get('zsybz'), 'zszzPfwy'),
                'zszz_hxkn': nullablea_dict(params.get('zsybz'), 'zszzHxkn'),
                'zszz_ty': nullablea_dict(params.get('zsybz'), 'zszzTy'),
                'zszz_yh': nullablea_dict(params.get('zsybz'), 'zszzYh'),
                'zszz_fr': nullablea_dict(params.get('zsybz'), 'zszzFr'),
                'zszz_tdyc': nullablea_dict(params.get('zsybz'), 'zszzTdyc'),
                'zszz_sktt': nullablea_dict(params.get('zsybz'), 'zszzSktt'),
                'zszz_qt_text': nullablea_dict(params.get('zsybz'), 'zszzQt'),
                'cgjc_cgxm': nullablea_dict(params.get('jcxm'), 'cgjcxm'),
                'cgjc_fzxm': nullablea_dict(params.get('jcxm'), 'fzjcxm'),
                'gwsc_gwfxkg': nullablea_dict(params.get('gwsc'), 'gwscKg'),
                'gwsc_gwfx': nullablea_dict(params.get('gwsc'), 'gwys'),
                'gwpg_gxpg': nullablea_dict(params.get('gwpg'), 'gwpgGxpg'),
                'gwpg_gwys': nullablea_dict(params.get('gwpg'), 'gwpgGwys'),
                'zdzdyj_zd_text': nullablea_dict(params.get('zdyzdyj'), 'zdqt'),
                'zdzdyj_zdyj_text': nullablea_dict(params.get('zdyzdyj'), 'zdyj'),
                'zdzdyj_bjzd_text': nullablea_dict(params.get('zdyzdyj'), 'bjzd'),
                'cl_zz': nullablea_dict(params.get('cl'), 'clZz'),
                'cl_zzyy': nullablea_dict(params.get('cl'), 'clZzyy'),
                'cl_zzjg': nullablea_dict(params.get('cl'), 'clZzjg'),
                'cl_zzks': nullablea_dict(params.get('cl'), 'clZzks'),
                'cl_yy': nullablea_dict(params.get('cl'), 'clYy'),
                # 'cl_xccjsj': nullablea_dict(params.get('cl'), 'clXccjsj'),
                # 'cl_zdsj': nullablea_dict(params.get('cl'), 'clZdsj'),
                'cl_ys_id': nullablea_dict(params.get('cl'), 'clYsId'),
                # 'cl_ys_name': nullablea_dict(params.get('cl'), 'clYsName'),
                'cj_pg': nullablea_dict(params.get('cl'), 'pg'),
                'cj': nullablea_dict(params.get('cl'), 'cl')
            }
            if nullablea_dict(params.get('cl'), 'clZdsj'):
                data_['cl_zdsj'] = nullablea_dict(params.get('cl'), 'clZdsj')
            if nullablea_dict(params.get('cl'), 'clXccjsj'):
                data_['cl_xccjsj'] = nullablea_dict(params.get('cl'), 'clXccjsj')
            main_id = odoo.env['inspection.diagnostic'].create(data_)
            create_event = event_type.OperationLogEvent('新增诊断处理', '档案id:{}'.format(params.get('archivesId')))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            logId = None
            if check_res['logId']:
                logId = check_res['logId']
                # 查询log表
                log_record = odoo.env['inspection.log'].search_read([('id', '=', int(logId))])
                if not log_record:
                    return jsonify({
                        "code": 1,
                        "msg": "请先进行其他检查"
                    })
                else:
                    log_record = log_record.pop()
                    flag = log_record['tgjx_id'] and log_record['sys_id'] and (log_record['cjda_id'] if log_record['type'] == '1' else log_record['wx_id'])
                    if not flag:
                        return jsonify({
                            "code": 1,
                            "msg": "请先进行其他检查"
                        })
                # 'sccjrq'
                # 更新log表 并归档该体检
                odoo.env['inspection.log'].write(logId, { 'zdcl_id': main_id, 'state': '1' })
                create_event = event_type.OperationLogEvent('更新log记录','logid:{},zdcl_id{}'.format(logId, main_id))
                message_bus = MessageBusManager().get_message_bus()
                message_bus.handle(create_event)  # 发布事件

                res_archives = odoo.env['res.archives'].search_read([('id', '=', int(params.get('archivesId')))])
                res_archives = res_archives.pop()
                gwys_ids = []
                for item in json.loads(nullablea_dict(params.get('gwsc'), 'gwys')):
                    gwys_ids.append(item['id'])
                # 更新档案
                update_info = {
                    # 上次产检时间
                    'sccjrq': tools.from_string(tools.context_today()).strftime('%Y-%m-%d'),
                    # 高危因素
                    'gwys_ids': gwys_ids,
                    # 档案状态
                    'status': 0
                }
                if (params.get('checkType') == '1'):
                    # 初检档案信息
                    cj_info = odoo.env['inspection.initial'].search_read([('id', '=', int(log_record['cjda_id'][0]))])
                    if cj_info:
                        cj_info = cj_info.pop()
                        update_info['mcyjsj'] = cj_info['rsqk_mcyjss']
                if params.get('checkType') == '3':
                    update_info['status'] = '1'
                if data_['gwpg_gwys'] and int(res_archives['max_gwys']) < int(data_['gwpg_gwys']):
                    update_info['max_gwys'] = data_['gwpg_gwys']
                if data_['gwpg_gwys']:
                    update_info['danger_color'] = data_['gwpg_gwys']
                update_archives(params.get('archivesId'), update_info)
            else:
                # 创建检查记录
                # check_data_ = {
                #     'archives_id': params.get('archivesId'),
                #     'type': params.get('checkType'),
                #     'wx_id': main_id,
                #     'state': '0'
                # }
                # check_data_ = odoo.env['inspection.log'].create(check_data_)
                # create_event = event_type.OperationLogEvent('创建检查记录', '档案id:{},zdcl_id{}'.format(params.get('archivesId'),main_id))
                # message_bus = MessageBusManager().get_message_bus()
                # message_bus.handle(create_event)  # 发布事件
                return jsonify({
                    "code": 1,
                    "msg": "请先进行其他检查"
                })
            # 更新增诊断处理logid
            u_data_ = { 'inspection_log_id': logId }
            odoo.env['inspection.diagnostic'].write(main_id, u_data_)
            create_event = event_type.OperationLogEvent('更新增诊断处理logid', '档案id:{}'.format(params.get('archivesId')))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            return jsonify({'code': 0, 'msg': 'success', 'data': { 'logId': logId, 'id': main_id }, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class DiagnosticRecordUpdateAPI(Resource):
    """
    修改诊断处理
    :request: put
    :param archivesId: 档案ID
    :param logId: logid
    :param checkType: 类型 1 初检 2常规 3 产后42天
    :param zsybz: 主诉与病状
            {
                "zszzFt": 腹痛
                "zszzYdcx": 阴道出血
                "zszzYdyy": 阴道溢液
                "zszzPfwy": 皮肤瘟痒
                "zszzHxkn": 呼吸困难
                "zszzTy": 头晕
                "zszzYh": 眼花
                "zszzFr": 发热
                "zszzTdyc": 胎动异常
                "zszzSktt": 伤口疼痛
                "zszzQt": 其他
            }
    :param gwsc: 高危筛查
            {
                "gwscKg": 高危因素判定开关
                "gwys": 高危因素
                    [
                        {
                            "gwysflCode": 高危因素分类编码
                            "gwysflName": 高危因素分类名
                            "gwysBm": 高危因素编码
                            "gwysMc": 高危因素名称
                            "gwColor": 高危因素颜色
                            "gwColorCode": 高危因素颜色编码
                        }
                    ]
            }
    :param gwpg: 高危评估
            {
                "gwpgGxpg": 高危颜色-开关-1 0
                "gwpgGwys": 高危评估颜色
            }
    :param jcxm: 常规检查项目
            {
                "cgjcxm": 常规检查项目
                    [
                        {
                            "cgjcxmCode": 常规检查项目编码
                            "cgjcxmName": 常规检查项目名称
                        }
                    ],
                "fzjcxm": 辅助检查项目
                    [
                        {
                            "fzjcxmCode": 辅助检查项目编码
                            "fzjcxmName": 辅助检查名称
                        }
                    ]
            }
    :param zdyzdyj: 诊断与指导意见
            {
                "yc": 孕次
                "cc": 产次
                "yz": 孕周
                "zd": 诊断
                "zdyj": 知道意见
                "bjzd": 保健指导
                    [
                        {
                            "bjzdCode": 保健指导CODE
                            "bjzdName": 保健指导名称
                        }
                    ]
            }
    :param cl: 处理
            {
                "clZz": 是否转诊
                "clZzjg": 转诊机构
                "clZzks": 转诊科室
                "clZzyy": 转诊原因
                "clYy": 是否预约
                "clXccjsj": 下次产检时间
                "clZdsj": 诊断时间
                "clYsId": 医生ID
                "clYsName": 医生姓名
                "pg": 评估 产后42天才有
                "cl": 处理 产后42天才有
            }
    :returns: json string
    """
    def put(self):
        try:
            odoo = OdooManager().get_instance()
            params = request.json
            # 参数校验
            req_params = ['archivesId','logId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            check_res = is_checking(params.get("archivesId"), params.get('checkType'))
            if not check_res['res'] and not params.get('history'):
                return jsonify({
                    'code': 1,
                    'msg': check_res['msg'],
                    'data': None
                })
            #  修改诊断处理
            data_ = {
                'inspection_log_id': params.get('logId'),
                'archives_id': params.get('archivesId'),
                'type': params.get('checkType'),
                'zszz_ft': nullablea_dict(params.get('zsybz'), 'zszzFt'),
                'zszz_ydcx': nullablea_dict(params.get('zsybz'), 'zszzYdcx'),
                'zszz_ydyy': nullablea_dict(params.get('zsybz'), 'zszzYdyy'),
                'zszz_pfwy': nullablea_dict(params.get('zsybz'), 'zszzPfwy'),
                'zszz_hxkn': nullablea_dict(params.get('zsybz'), 'zszzHxkn'),
                'zszz_ty': nullablea_dict(params.get('zsybz'), 'zszzTy'),
                'zszz_yh': nullablea_dict(params.get('zsybz'), 'zszzYh'),
                'zszz_fr': nullablea_dict(params.get('zsybz'), 'zszzFr'),
                'zszz_tdyc': nullablea_dict(params.get('zsybz'), 'zszzTdyc'),
                'zszz_sktt': nullablea_dict(params.get('zsybz'), 'zszzSktt'),
                'zszz_qt_text': nullablea_dict(params.get('zsybz'), 'zszzQt'),
                'cgjc_cgxm': nullablea_dict(params.get('jcxm'), 'cgjcxm'),
                'cgjc_fzxm': nullablea_dict(params.get('jcxm'), 'fzjcxm'),
                'gwsc_gwfxkg': nullablea_dict(params.get('gwsc'), 'gwscKg'),
                'gwsc_gwfx': nullablea_dict(params.get('gwsc'), 'gwys'),
                'gwpg_gxpg': nullablea_dict(params.get('gwpg'), 'gwpgGxpg'),
                'gwpg_gwys': nullablea_dict(params.get('gwpg'), 'gwpgGwys'),
                'zdzdyj_zd_text': nullablea_dict(params.get('zdyzdyj'), 'zdqt'),
                'zdzdyj_zdyj_text': nullablea_dict(params.get('zdyzdyj'), 'zdyj'),
                'zdzdyj_bjzd_text': nullablea_dict(params.get('zdyzdyj'), 'bjzd'),
                'cl_zz': nullablea_dict(params.get('cl'), 'clZz'),
                'cl_zzyy': nullablea_dict(params.get('cl'), 'clZzyy'),
                'cl_zzjg': nullablea_dict(params.get('cl'), 'clZzjg'),
                'cl_zzks': nullablea_dict(params.get('cl'), 'clZzks'),
                'cl_yy': nullablea_dict(params.get('cl'), 'clYy'),
                # 'cl_xccjsj': nullablea_dict(params.get('cl'), 'clXccjsj'),
                # 'cl_zdsj': nullablea_dict(params.get('cl'), 'clZdsj'),
                'cl_ys_id': nullablea_dict(params.get('cl'), 'clYsId'),
                # 'cl_ys_name': nullablea_dict(params.get('cl'), 'clYsId')[1] if nullablea_dict(params.get('cl'), 'clYsId') else None,
                'cj_pg': nullablea_dict(params.get('cl'), 'pg'),
                'cj': nullablea_dict(params.get('cl'), 'cl')
            }
            if nullablea_dict(params.get('cl'), 'clZdsj'):
                data_['cl_zdsj'] = nullablea_dict(params.get('cl'), 'clZdsj')
            if nullablea_dict(params.get('cl'), 'clXccjsj'):
                data_['cl_xccjsj'] = nullablea_dict(params.get('cl'), 'clXccjsj')
            query_ = [
                ('archives_id', '=', int(params.get('archivesId'))),
                ('inspection_log_id', '=', int(params.get('logId')))
            ]
            inspection_diagnostic = odoo.env['inspection.diagnostic'].search(query_)
            if not inspection_diagnostic:
                return jsonify({'code': 40005, 'msg': error_code[40005]})  
            odoo.env['inspection.diagnostic'].write(inspection_diagnostic,data_)
            create_event = event_type.OperationLogEvent('修改诊断处理', '档案id:{}'.format(params.get('archivesId')))
            message_bus = MessageBusManager().get_message_bus()
            message_bus.handle(create_event)  # 发布事件
            # 查询当前log是否为最新的一条 如果是则更新数据
            logs = odoo.env['inspection.log'].search_read([('archives_id', '=', int(params.get('archivesId')))])
            if logs:
                log = logs.pop()
                if log['id'] == int(params.get('logId')):
                    res_archives = odoo.env['res.archives'].search_read(
                        [('id', '=', int(params.get('archivesId')))])
                    res_archives = res_archives.pop()
                    gwys_ids = []
                    for item in json.loads(nullablea_dict(params.get('gwsc'), 'gwys')):
                        gwys_ids.append(item['id'])
                    # 清空档案之前的高危因素关联信息
                    # odoo.env['res.archives.gwys.ref'].unlink(res_archives['gwys_ids'])
                    # 更新档案
                    update_info = {
                        # 上次产检时间
                        'sccjrq': tools.from_string(tools.context_today()).strftime('%Y-%m-%d'),
                        # 高危因素
                        'gwys_ids': [(6, 0, gwys_ids)],
                        # 档案状态
                        'status': 0
                    }
                    if params.get('checkType') == '1':
                        # 初检档案信息
                        cj_info = odoo.env['inspection.initial'].search_read([('id', '=', int(log['cjda_id'][0]))])
                        if cj_info:
                            cj_info = cj_info.pop()
                            update_info['mcyjsj'] = cj_info['rsqk_mcyjss']
                    if params.get('checkType') == '3':
                        update_info['status'] = '1'
                    if data_['gwpg_gwys'] and int(res_archives['max_gwys']) < int(data_['gwpg_gwys']):
                        update_info['max_gwys'] = data_['gwpg_gwys']
                    if data_['gwpg_gwys']:
                        update_info['danger_color'] = data_['gwpg_gwys']
                    update_archives(params.get('archivesId'), update_info)
            return jsonify({'code': 0, 'msg': 'success', 'data': {'logId': params.get('logId'),'id': inspection_diagnostic[0]}, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class DiagnosticRecordQueryInsHisAPI(Resource):
    """
    档案ID查询诊断处理 或 根据logid历史记录
    :request: get
    :param archivesId: 档案ID
    :param logId: 针对历史记录的需要传
    :param type: NULL 不区分 0 在途 1完成
    :param checkType: 1 初检 2 常规 3 产后42天
    :returns: json string
    """
    def get(self):
        try:
            #  获取孕妇建档信息
            odoo = OdooManager().get_instance()
            query_ = []
            params = request.values
            if  params.get('archivesId'):
                query_.append(('archives_id', '=', int(params.get('archivesId')))) 
            if  params.get('logId'):
                c_query_ = [
                    ('state', '=', '1'),
                    ('archives_id', '=',int(params.get('archivesId'))),
                    ('id', '=',int(params.get('logId')))
                ]
                inspection_log = odoo.env['inspection.log'].search_read(c_query_, ['zdcl_id'])
                if inspection_log:
                    inspection_log = inspection_log.pop()
                    query_.append(('id', '=', int(inspection_log['zdcl_id'][0])))
            else:
                # 查询档案在途的诊断处理
                res = odoo.env['inspection.log'].search_read([
                    ('archives_id', '=', int(params.get('archivesId'))),
                    ('state', '=', '0'),
                    ('type', '=', params.get('checkType'))
                ])
                if (res):
                    res = res.pop()
                    if (res['zdcl_id']):
                        # 将初检档案Id append到查询条件中去
                        query_.append(('id', '=', int(res['zdcl_id'][0])))
                    else:
                        return {
                            'msg': 'success',
                            'code': 0,
                            'data': None
                        }
                else:
                    return {
                        'msg': 'success',
                        'code': 0,
                        'data': None
                    }
            if  params.get('checkType'):
                query_.append(('type', '=', int(params.get('checkType'))))       
            data_ = {}
            inspection_diagnostic = odoo.env['inspection.diagnostic'].search_read(query_)
            if inspection_diagnostic:
                inspection_diagnostic = inspection_diagnostic.pop()
                data_ = {
                    'logId': inspection_diagnostic['inspection_log_id'][0],
                    'checkType': inspection_diagnostic['type'],
                    'zsybz': {
                        'zszzFt': inspection_diagnostic['zszz_ft'],
                        'zszzYdcx': inspection_diagnostic['zszz_ydcx'],
                        'zszzYdyy': inspection_diagnostic['zszz_ydyy'],
                        'zszzPfwy': inspection_diagnostic['zszz_pfwy'],
                        'zszzHxkn': inspection_diagnostic['zszz_hxkn'],
                        'zszzTy': inspection_diagnostic['zszz_ty'],
                        'zszzYh': inspection_diagnostic['zszz_yh'],
                        'zszzFr': inspection_diagnostic['zszz_fr'],
                        'zszzTdyc': inspection_diagnostic['zszz_tdyc'],
                        'zszzSktt': inspection_diagnostic['zszz_sktt'],
                        'zszzQt': inspection_diagnostic['zszz_qt_text']
                    },
                    'gwsc': {
                        'gwscKg': inspection_diagnostic['gwsc_gwfxkg'],
                        'gwys': inspection_diagnostic['gwsc_gwfx']
                    },
                    'gwpg': {
                        'gwpgGxpg': inspection_diagnostic['gwpg_gxpg'],
                        'gwpgGwys': inspection_diagnostic['gwpg_gwys']
                    },
                    'jcxm': {
                        'cgjcxm': inspection_diagnostic['cgjc_cgxm'],
                        'fzjcxm': inspection_diagnostic['cgjc_fzxm']
                    },
                    'zdyzdyj': {
                        'yc': 'string',
                        'cc': 'string',
                        'yz': 'string',
                        'zdqt': inspection_diagnostic['zdzdyj_zd_text'],
                        'zdyj': inspection_diagnostic['zdzdyj_zdyj_text'],
                        'bjzd': inspection_diagnostic['zdzdyj_bjzd_text']
                    },     
                    'cl': {
                    'clZz': inspection_diagnostic['cl_zz'],
                    'clZzjg': inspection_diagnostic['cl_zzjg'][0] if inspection_diagnostic['cl_zzjg'] else None,
                    'clZzks': inspection_diagnostic['cl_zzks'],
                    'clZzyy': inspection_diagnostic['cl_zzyy'],
                    'clYy': inspection_diagnostic['cl_yy'],
                    'clXccjsj': inspection_diagnostic['cl_xccjsj'],
                    'clZdsj': inspection_diagnostic['cl_zdsj'],
                    'clYsId': inspection_diagnostic['cl_ys_id'][0] if inspection_diagnostic['cl_ys_id'] else None,
                    'clYsName': inspection_diagnostic['cl_ys_id'][1] if inspection_diagnostic['cl_ys_id'] else None,
                    'pg': inspection_diagnostic['cj_pg'],
                    'cl': inspection_diagnostic['cj']
                    }
                }
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class DiagnosticRecordQueryHisAPI(Resource):
    """
    诊断处理左侧时间线
    :request: post
    :param archivesId: 档案ID
    :param examinationTimeStart: 检查开始日期
    :param examinationTimeEnd: 检查结束日期
    :param isAsc：排序方向 排序的方向,示例值(asc,desc)
    :param orderByColumn：排序列
    :param pageNum：当前页数
    :param pageSize: 分页大小
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            # 参数校验
            req_params = ['archivesId']
            vrf_res = tools.required_parame_verif(req_params,params)
            if  vrf_res['code'] != 0:
                return jsonify(vrf_res)
            is_asc = params.get('isAsc') if params.get('isAsc', False) else 'asc'
            order_by_column = params.get('orderByColumn') if params.get('orderByColumn', False) else 'create_date'
            #  构造排序方式
            order_ = order_by_column+' '+ is_asc
            #  初始化页数,返回数据条数,偏移
            page = int(params.get('pageNum')) if params.get('pageNum', False) else 1
            pagesize = int(params.get('pageSize')) if params.get('pageSize', False) else 10
            offset = page * pagesize - pagesize
            #  构造查询条件 status
            query_ = [('archives_id', '=', int(params.get('archivesId')))]

            #  建档环节
            if params.get('examinationTimeStart'): # 检查开始日期
                query_.append(('jd_date', '>=', params.get('examinationTimeStart')))   
            if params.get('examinationTimeEnd'): # 检查结束日期
                query_.append(('jd_date', '<=', params.get('examinationTimeEnd')))   
            data_ = []    
            fields = [
                    'mq_xm','mq_sfz','mq_mz','mq_jt_address','jd_date','yz','jd_dw'
                    ]    
            res_archives = odoo.env['res.archives'].search_read(query_,fields,  offset = offset, limit = pagesize, order = order_)
            if res_archives:
                for  res_archives_ in res_archives:
                    data_tmp={
                            'jcSj': res_archives_['jd_date'],
                            'yz': res_archives_['yz'],
                            'jcName': res_archives_['jd_dw'][-1],
                            'jcJg': res_archives_['jd_dw'][0],
                            'jcType': '1',
                            'jd': {
                                'xm': res_archives_['mq_xm'],
                                'idCard': res_archives_['mq_sfz'],
                                'nation': res_archives_['mq_mz'],
                                'addr': res_archives_['mq_jt_address']
                            },
                            
                    }
                    data_.append(data_tmp)
            #  初检环节
            if params.get('examinationTimeStart'): # 检查开始日期
                query_.append(('jws_jcsj', '>=', params.get('examinationTimeStart')))   
            if params.get('examinationTimeEnd'): # 检查结束日期
                query_.append(('jws_jcsj', '<=', params.get('examinationTimeEnd')))     
            fields = [
                    'jws_jcsj','jbxx_jcjg','rsqk_yz','mq_jt_address','jd_date','yz','jd_dw'
                    ]    
            inspection_initial = odoo.env['inspection.initial'].search_read(query_,fields,  offset = offset, limit = pagesize, order = order_)
            if inspection_initial:
                inspection_initial_ = inspection_initial[0]
                #  体格检查
                query_=[
                    ('inspection_log_id','=',int(inspection_initial_['inspection_log_id'])),
                    ('archives_id', '=', int(params.get('archivesId')))
                ]
                fields = [
                    'cg_sg','cg_tz','cg_yqtz','cg_yqbmi'
                ] 
                inspection_physical = odoo.env['inspection.physical'].search_read(query_,fields,  offset = offset, limit = pagesize, order = order_)
                #  诊断处理 -初检
                query_=[
                    ('inspection_log_id','=',int(inspection_initial_['inspection_log_id'])),
                    ('archives_id', '=', int(params.get('archivesId'))),
                    ('type', '=', 1)
                ]
                fields = [
                    'cl_zzyy','cg_tz','cg_yqtz','gwpg_gwys','zdzdyj_zd_text','gwsc_gwfxkg'
                ] 
                inspection_diagnostic = odoo.env['inspection.diagnostic'].search_read(query_,fields,  offset = offset, limit = pagesize, order = order_)
                
                data_tmp={
                        'jcSj': inspection_initial_['jws_jcsj'],
                        'yz': inspection_initial_['rsqk_yz'],
                        'jcName': inspection_initial_['jbxx_jcjg'][-1],
                        'jcJg': inspection_initial_['jbxx_jcjg'][0],
                        'jcType': '2',
                        'cj': {
                            'sg': inspection_physical[0]['cg_sg'] if inspection_physical else '',
                            'tz': inspection_physical[0]['cg_tz'] if inspection_physical else '',
                            'yqtz': inspection_physical[0]['cg_yqtz'] if inspection_physical else '',
                            'yqBmi': inspection_physical[0]['cg_yqbmi'] if inspection_physical else '',
                            'zd': inspection_diagnostic[0]['zdzdyj_zd_text'] if inspection_diagnostic else '',
                            'gwys': inspection_diagnostic[0]['gwsc_gwfxkg'] if inspection_diagnostic else '',    
                            'gwColor': inspection_diagnostic[0]['gwpg_gwys'] if inspection_diagnostic else '',
                            'gwColorCode': inspection_diagnostic[0]['gwpg_gwys'] if inspection_diagnostic else '',
                            'zz': {
                                'zzyy': inspection_diagnostic[0]['cl_zzyy'] if inspection_diagnostic else '',
                                'zzjg': inspection_diagnostic[0]['cl_zzjg'] if inspection_diagnostic else '',
                                'zzks': inspection_diagnostic[0]['cl_zzks'] if inspection_diagnostic else ''
                            }    
                        },
                        
                }
                data_.append(data_tmp)
                #  诊断处理-常规
                query_=[
                    ('inspection_log_id','=',int(inspection_initial_['inspection_log_id'])),
                    ('archives_id', '=', int(params.get('archivesId'))),
                    ('type', '=', 2)
                ]
                if params.get('examinationTimeStart'): # 检查开始日期
                    query_.append(('cl_zdsj', '>=', params.get('examinationTimeStart')))   
                if params.get('examinationTimeEnd'): # 检查结束日期
                    query_.append(('cl_zdsj', '<=', params.get('examinationTimeEnd')))
                fields = [
                    'hospital_id','cl_zdsj','cl_zzyy','cg_tz','cg_yqtz','gwpg_gwys','zdzdyj_zd_text','gwsc_gwfxkg'
                ] 
                inspection_diagnostic = odoo.env['inspection.diagnostic'].search_read(query_,fields,  offset = offset, limit = pagesize, order = order_)
                
                data_tmp={
                        'jcSj': inspection_initial_['cl_zdsj'],
                        'yz': inspection_initial_['rsqk_yz'],
                        'jcName': inspection_initial_['hospital_id'][-1],
                        'jcJg': inspection_initial_['hospital_id'][0],
                        'jcType': '3',
                        'jcjbxx': {
                            'zd': inspection_diagnostic[0]['zdzdyj_zd_text'] if inspection_diagnostic else '',
                            'gwys': inspection_diagnostic[0]['gwsc_gwfxkg'] if inspection_diagnostic else '',    
                            'gwColor': inspection_diagnostic[0]['gwpg_gwys'] if inspection_diagnostic else '',
                            'gwColorCode': inspection_diagnostic[0]['gwpg_gwys'] if inspection_diagnostic else '',
                            'zz': {
                                'zzyy': inspection_diagnostic[0]['cl_zzyy'] if inspection_diagnostic else '',
                                'zzjg': inspection_diagnostic[0]['cl_zzjg'] if inspection_diagnostic else '',
                                'zzks': inspection_diagnostic[0]['cl_zzks'] if inspection_diagnostic else ''
                            }    
                        },
                        
                }
                data_.append(data_tmp)
                #  诊断处理-产后42天都有
                query_=[
                    ('inspection_log_id','=',int(inspection_initial_['inspection_log_id'])),
                    ('archives_id', '=', int(params.get('archivesId'))),
                    ('type', '=', 3)
                ]
                if params.get('examinationTimeStart'): # 检查开始日期
                    query_.append(('cl_zdsj', '>=', params.get('examinationTimeStart')))   
                if params.get('examinationTimeEnd'): # 检查结束日期
                    query_.append(('cl_zdsj', '<=', params.get('examinationTimeEnd')))
                fields = [
                    'hospital_id','cl_zdsj','cl_zzyy','cg_tz','cg_yqtz','gwpg_gwys','zdzdyj_zd_text','gwsc_gwfxkg'
                ] 
                inspection_diagnostic = odoo.env['inspection.diagnostic'].search_read(query_,fields,  offset = offset, limit = pagesize, order = order_)
                
                data_tmp={
                        'jcSj': inspection_initial_['cl_zdsj'],
                        'yz': inspection_initial_['rsqk_yz'], 
                        'jcName': inspection_initial_['hospital_id'][-1],
                        'jcJg': inspection_initial_['hospital_id'][0],
                        'jcType': '7',
                        'jcjbxx': {
                            'zd': inspection_diagnostic[0]['zdzdyj_zd_text'] if inspection_diagnostic else '',
                            'gwys': inspection_diagnostic[0]['gwsc_gwfxkg'] if inspection_diagnostic else '',    
                            'gwColor': inspection_diagnostic[0]['gwpg_gwys'] if inspection_diagnostic else '',
                            'gwColorCode': inspection_diagnostic[0]['gwpg_gwys'] if inspection_diagnostic else '',
                            'zz': {
                                'zzyy': inspection_diagnostic[0]['cl_zzyy'] if inspection_diagnostic else '',
                                'zzjg': inspection_diagnostic[0]['cl_zzjg'] if inspection_diagnostic else '',
                                'zzks': inspection_diagnostic[0]['cl_zzks'] if inspection_diagnostic else ''
                            }    
                        },
                        
                }
                data_.append(data_tmp)
            # 分娩  :分娩时间 检查条件日期可能不对 目前以宫缩时间为依据
            query_=[
                    ('archives_id', '=', int(params.get('archivesId'))),
            ] 
            if params.get('examinationTimeStart'): # 检查开始日期
                query_.append(('dycc_gs_time', '>=', params.get('examinationTimeStart')))   
            if params.get('examinationTimeEnd'): # 检查结束日期
                query_.append(('dycc_gs_time', '<=', params.get('examinationTimeEnd')))  
            fields = [
                    'hospital_id','dycc_gs_time','cf_ts','cf_cb','cf_yz_week'
            ]  
            birth_record = odoo.env['birth.record'].search_read(query_,fields,  offset = offset, limit = pagesize, order = order_)
            if birth_record:
                birth_record = birth_record[0]
                data_tmp={
                        'jcSj': birth_record['dycc_gs_time'],
                        'yz': birth_record['cf_yz_week'], 
                        'jcName': birth_record['hospital_id'][-1],
                        'jcJg': birth_record['hospital_id'][0],
                        'jcType': '6',
                        'fm': {
                            'fmTime': birth_record['dycc_gs_time'],
                            'fmts': birth_record['cf_ts'],    
                            'fmfs': birth_record['cf_cb'],
                        },
                        
                }
                data_.append(data_tmp)

            #  产前筛查-糖耐
            query_=[
                    ('archives_id', '=', int(params.get('archivesId'))),
            ] 
            if params.get('examinationTimeStart'): # 检查开始日期
                query_.append(('dycc_gs_time', '>=', params.get('examinationTimeStart')))   
            if params.get('examinationTimeEnd'): # 检查结束日期
                query_.append(('dycc_gs_time', '<=', params.get('examinationTimeEnd')))  
            if params.get('examinationTimeStart'): # 检查开始日期
                query_.append(('jc_date', '>=', params.get('examinationTimeStart')))   
            if params.get('examinationTimeEnd'): # 检查结束日期
                query_.append(('jc_date', '<=', params.get('examinationTimeEnd'))) 
            fields = [
                    'sc_jg','jc_date','jc_jg'
                    ]    
            records = odoo.env['inspection.nt.screen'].search_read(query_,fields,  offset = offset, limit = pagesize, order = order_)
            if records:
                record_ = records[0]
                # OGTT
                fields = [
                    'sc_jg'
                ] 
                sugar = odoo.env['inspection.sugar.resistance'].search_read(query_,fields,  offset = offset, limit = pagesize, order = order_)
                gene = odoo.env['inspection.gene'].search_read(query_,fields,  offset = offset, limit = pagesize, order = order_)
                ultrasonics = odoo.env['inspection.ultrasonics'].search_read(query_,fields,  offset = offset, limit = pagesize, order = order_)
                data_tmp={
                    'jcSj': record_['jc_date'],
                    'yz': '',
                    'jcName': record_['jc_jg'][-1],
                    'jcJg': record_['jc_jg'][0],
                    'jcType': '5',
                    'cqsc': {
                        'NT': record_['sc_jg'],
                        'OGTT': sugar[0]['sc_jg'] if sugar else '',
                        'teqxbc': gene[0]['sc_jg'] if gene else '',
                        'gtjycx': ultrasonics[0]['sc_jg'] if ultrasonics else ''
                    },
                    
                }
                
                data_.append(data_tmp)
                
            #  4-产前筛查与诊断-唐筛 ：没有数据结构
            
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class DiaHighRiskFacTypeListAPI(Resource):
    """
    高危风险筛查页面左侧列表分类查询
    :request: get
    :returns: json string
    """
    def _get(self,parent_id=None):
        odoo = OdooManager().get_instance()
        fields = [
                    'name','id','code','color'
                    ] 
        query_ = [('parent_id', '=', parent_id)]
        data_ = []
        dict_gwys = odoo.env['dict.gwys'].search_read(query_,fields)
        # 设置层数减少递归 增加查询速度
        num=0
        while num<1:
            if dict_gwys:
                for gwys_ in dict_gwys:
                    #print (gwys_)
                    if not gwys_['color']:
                        data_.append(
                            {
                                'gwysTypeName': gwys_['name'],
                                'gwysTypeCode': gwys_['code'],
                                'children': {} if gwys_['color'] else self._get(gwys_['id']),
                                'id': gwys_['id']
                            }
                        ) 
            num += 1            
        return  data_           
    def get(self):
        try:
            data_ = self._get() 
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})

class DiaHighRiskFacListAPI(Resource):
    """
    高危风险筛查页面右侧高危因素列表查询
    :request: post
    :param gwysTypeCode: 高危因素分类CODE
    :param fxLevel: 风险等级 一般风险 黄色 较高风险 橙色 高风险 红色 传染病 紫色
    :param searchText: 搜索内容
    :returns: json string
    """
    #@AppSecurity.public_verify()
    #@AppSecurity.token_verify()
    def post(self):
        try:
            odoo = OdooManager().get_instance()
            params = tools.get_params(request)
            #  构造查询条件
            query_ = []
            if params.get('gwysTypeId'):
                query_.append(('parent_id', 'in', params.get('gwysTypeId')))
            if params.get('fxLevel'):
                query_.append(('color', 'in', params.get('fxLevel')))
            if params.get('searchText'):
                query_.append(('name', 'like', params.get('searchText')))
            fields = [
                    'name','id','code','color', 'parent_id'
                    ]   
            dict_gwys = odoo.env['dict.gwys'].search_read(query_,fields)
            data_ = []
            if dict_gwys:
                for gwys_ in dict_gwys:
                    dict_gwys_ = None
                    query_ = [('id', '=', int(gwys_['parent_id'][0]))]
                    dict_gwys_ = odoo.env['dict.gwys'].search_read(query_, fields)
                    if dict_gwys_:
                        dict_gwys_ = dict_gwys_.pop()
                    data_.append(
                        {
                            'gwysflCode': dict_gwys_['code'] if dict_gwys_ else params.get('gwysTypeCode'),
                            'gwysflName': dict_gwys_['name'] if dict_gwys_ else '',
                            'gwysBm': gwys_['code'],
                            'gwysMc': gwys_['name'],
                            'gwysColor': dict_handler.get_dict_value(gwys_['color'],'ck_gwys'),
                            'gwysCode': gwys_['color'],
                            'id': gwys_['id']
                        }
                    )
            return jsonify({'code': 0, 'msg': 'success', 'data': data_, 'success': True})
        except AttributeError as e:
            logging.exception(e)
            return jsonify({'code': 404, 'msg': error_code[404]})
        except Exception as e:
            logging.exception(e)
            return jsonify({'code': 100, 'msg': error_code[100]})


class GetCheckProject(Resource):
    """
    获取检查项目列表
    params:
        type string 项目类别
    """
    def get(self):
        try:
            odoo = OdooManager().get_instance()
            params = request.values
            query = []
            if (params.get('type')):
                query.append(('type', '=', params.get('type')))
            if (params.get('project_type')):
                query.append(('project_type', '=', params.get('project_type')))
            res = odoo.env['inspection.item'].search_read(query, ['name', 'code', 'project_type', 'type'])
            print(res)
            return jsonify({
                "code": 0,
                "data": res,
                "msg": 'success'
            })
        except Exception as e:
            print(e)
            return jsonify({
                "code": 100,
                "msg": error_code[100]
            })
